package com.njwb.day16.dom.util;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JdbcTemplate {


    //更新 (添加、修改、删除)
    public static int executeUpdate(String sql,Object...params) throws SQLException {
        int result = -1 ;
        //构建连接对象
        Connection connection= null ;
        //命令器
        PreparedStatement pstmt= null ;
        connection = DbUtil.getConnection();
        pstmt = connection.prepareStatement(sql);
        setParams(pstmt,params) ;
        result = pstmt.executeUpdate();
        DbUtil.closeResource(null,pstmt);
        return result ;
    }

    //设置参数
    public static void setParams(PreparedStatement pstmt,Object...params) throws  SQLException  {
        if(params!=null&&params.length>0) {
            for(int i = 0 ;i<params.length;i++) {
                pstmt.setObject(i+1,params[i]);
            }
        }
    }

    //查询多个数据
    public static <T> List<T> executeQueryAll(String sql,IRowMapper<T> rowMapper,Object...params) throws SQLException {
        List<T> list = new ArrayList<>();
        //构建连接对象
        Connection connection= null ;
        //命令器
        PreparedStatement pstmt= null ;
        //结果集
        ResultSet rs = null ;
        connection = DbUtil.getConnection();
        pstmt = connection.prepareStatement(sql);
        setParams(pstmt,params) ;
        rs = pstmt.executeQuery();
        while(rs.next()) {
            list.add(rowMapper.getInstanceByRow(rs));
        }
        DbUtil.closeResource(rs,pstmt);
        return list ;
    }

    //查询单条数据
    public static <T> T executeQueryOne(String sql,IRowMapper<T> rowMapper,Object...params) throws SQLException {
        List<T> list =executeQueryAll(sql,rowMapper,params);
        return list.size()==1?list.get(0):null ;
    }
}
